package dao

import (
	"myserver/model"
	"myserver/param"
	"myserver/tool"
)

type ReservationDao struct {
	*tool.MyOrm
}

func (d *ReservationDao) QueryReservation(query string) model.Reservation {
	var rest model.Reservation
	d.Db.Where("id = ?", query).First(&rest)
	return rest
}

func (d *ReservationDao) CreateReservation(reservation model.Reservation) int64 {
	res := d.Db.Create(&reservation)
	return res.RowsAffected
}

func (d *ReservationDao) DeleteReservation(reservation model.Reservation) int64 {
	res := d.Db.Delete(&reservation)
	return res.RowsAffected
}

func (d *ReservationDao) UpdateReservation(reservation model.Reservation) int64 {
	if reservation.Status == 1 {
		reservation.CheckMsg = "审核通过"
	}
	res := d.Db.Updates(&reservation)
	return res.RowsAffected
}

func (d *ReservationDao) QueryReservations(pageParam param.PageParam) param.ResponsePageParam {
	rs := param.ResponsePageParam{}
	rs.Data = []model.Reservation{}
	db := d.Db.Model(&model.Reservation{})
	if pageParam.SearchContent != "" {
		db = db.Where("reservation_name LIKE ?", "%"+pageParam.SearchContent+"%")
	}
	db.Order("ID ASC").Count(&rs.Total).Limit(pageParam.Limit).Offset(pageParam.Page).Find(&rs.Data)
	return rs
}

func (d *ReservationDao) CreateRsWork(pageParam param.PageParam) int64 {
	rs := model.Reservation{}
	rs.ResourceType = 2
	rs.CheckMsg = "未审核"
	rs.UserID = uint(pageParam.UserId)
	rs.Status = 0
	rs.Describe = pageParam.Describe
	rs.ResourceID = uint(pageParam.WorkId)
	rs.ReservationName = pageParam.ReservationName
	res := d.Db.Create(&rs)
	return res.RowsAffected
}

func (d *ReservationDao) CreateRsSubsidy(pageParam param.PageParam) interface{} {
	rs := model.Reservation{}
	rs.ResourceType = 1
	rs.CheckMsg = "未审核"
	rs.UserID = uint(pageParam.UserId)
	rs.Status = 0
	rs.Describe = pageParam.Describe
	rs.ResourceID = uint(pageParam.SubsidyId)
	rs.ReservationName = pageParam.ReservationName
	res := d.Db.Create(&rs)
	return res.RowsAffected
}

func (d *ReservationDao) QueryUserReservations(pageParam param.PageParam) param.ResponsePageParam {
	rs := param.ResponsePageParam{}
	rs.Data = []model.Reservation{}
	db := d.Db.Model(&model.Reservation{})
	db = db.Where("user_id = ?", pageParam.UserId)
	if pageParam.SearchContent != "" {
		db = db.Where("reservation_name LIKE ?", "%"+pageParam.SearchContent+"%")
	}
	db.Order("ID ASC").Count(&rs.Total).Limit(pageParam.Limit).Offset(pageParam.Page).Find(&rs.Data)
	return rs
}

func (d *ReservationDao) UpdateRefuseReservation(reservation model.Reservation) int64 {
	res := d.Db.Model(&reservation).Updates(model.Reservation{CheckMsg: "审核通过"})
	return res.RowsAffected
}
